<?php

namespace app\controller\factory;

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");


use app\Auth;
use app\BaseController;
use app\models\factory\Admin;
use app\models\factory\Order as orderModel;
use app\Request;
use lc\helpers\Curl;
use lc\helpers\Helper;
use lc\helpers\Response;
use think\facade\Db;
use DateTime;
use DateInterval;
use Qiniu\Auth as QiNiuAuth;
use Qiniu\Storage\UploadManager;
use think\route\Domain;


class Order extends BaseController
{

    /**
     * 入厂
     * @return void
     */

    public function joinFactory(Request $request)
    {

        $admin = Auth::$admin;
        $number = $request['number'];
        if (empty($number)) {
            return response::fail('请填写物流单号');
        }

        $update = [
            'status' => 1,
            'factory_time' => date('Y-m-d H:i:s', time()),
            'order_status'=>1,
            'staff_id'=>$admin->id,
            'store_id'=>$admin->store_id
        ];

        $orderData = Db::table('xd_store_order')->where('waybill_code|order_id', $number)->find();

        if (empty($orderData)) {
            return response::fail('未找到该订单');
        }

        if($orderData['status'] == 1){
            return response::fail('该订单已签收');
        }

        if ($orderData['status'] == 0) {
            $arr1 = [
                'status' => '1',
                'add_time' => date('Y-m-d H:i:s')
            ];
        } else {
            $arr1 = [
                'status' => '1',
            ];
        }

        Db::table('xd_store_order_goodsInfo')->where('oid', $orderData['id'])->update($arr1);
        Db::table('xd_store_order')->where('id', $orderData['id'])->update($update);

        return response::success();
    }


    /**
     * 根据物流单号返回订单信息
     * @return void
     */
    public function getOrderDataTwo(Request $request)
    {
     $admin = Auth::$admin;

        $number = $request['number'];

        if (empty($number)) {
            return response::fail('物流单号不能为空');
        }

        $orderData = DB::table('xd_store_order')->where('paid', '1')->where('waybill_code|order_id', $number)->find();

        if (!empty($orderData)) {
            if ($orderData['refund_status'] == '0') {
                $orderData['add_time'] = date('Y-m-d H:i:s',$orderData['add_time']);
                $orderData['goods'] = Db::table('xd_store_order_goodsInfo')->where('oid', $orderData['id'])->select()->each(function ($item){
                    $item['pic'] = json_decode($item['pic']);
                    $item['goods_flaw'] = json_decode($item['goods_flaw']);
                    $item['fidjson'] = json_decode($item['fidjson']);
                    return $item;
                })->toArray();
                return response::success($orderData);
            } else {
                return response::fail('订单已退款，请联系客服处理，谢谢！');
            }

        } else {
            return response::fail('查询不到该订单');
        }
    }


    /**
     * 当日签收数据
     */

    public function todayData(Request $request){

        $admin = Auth::$admin;
        $size = $request['limit'] ?? 15;
        $search = $request['title'];
        $startDate = $request['startDate'];
        $endDate = $request['endDate'];

        if($admin->roles == 0){
            $where = [
                ['store_id','=',$admin->store_id],
                ['order_status','>=',1]
            ];
        }else{
            $where = [
//                ['staff_id','=',$admin->id],
                ['store_id','=',$admin->store_id],
                ['order_status','>=',1]
            ];
        }

        $data = Db::table('xd_store_order')
            ->where($where)
            ->whereLike('waybill_code|id','%'.$search.'%');
        if(!empty($startDate)){
            $data = $data->whereBetweenTime('factory_time',$startDate,$endDate);
        }
        $data = $data->order('factory_time','desc')
            ->order('id','desc')
//            ->whereBetweenTime('factory_time',date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59'))
            ->paginate($size)->each(function ($item){
                $item['add_time'] = date('Y-m-d H:i:s',$item['add_time']);
                return $item;
            });

        return response::success($data);
    }


    public function todaySignData(Request $request){

        $admin = Auth::$admin;
        $size = $request['limit'] ?? 15;
        $search = $request['title'];

       $where = [
           ['staff_id','=',$admin->id],
       ];

        $data = Db::table('xd_store_order')
            ->where($where)
            ->whereLike('waybill_code','%'.$search.'%')
            ->order('factory_time','desc')
            ->whereBetweenTime('factory_time',date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59'))
            ->paginate($size)->each(function ($item){
                $item['add_time'] = date('Y-m-d H:i:s',$item['add_time']);
                return $item;
            });

        return response::success($data);
    }

    /**
     * 根据物流单号返回订单信息
     * @return void
     */
    public function getOrderData(Request $request)
    {

        $number = $request['number'];
//
        if (empty($number)) {
            return response::fail('物流单号不能为空');
        }

        $orderData = DB::table('xd_store_order')->where('paid', '1')->where('waybill_code|order_id|id', $number)->find();

        if (!empty($orderData)) {
            if ($orderData['refund_status'] == '0') {
                $orderData['add_time'] = date('Y-m-d H:i:s',$orderData['add_time']);
                $orderData['goods'] = Db::table('xd_store_order_goodsInfo')->where('oid', $orderData['id'])->select()->each(function ($item){
                    $item['pic'] = json_decode($item['pic']);
                    $item['goods_flaw'] = json_decode($item['goods_flaw']);
                    $item['fidjson'] = json_decode($item['fidjson']);
                    if($item['is_wash'] == 1){
                        $item['is_wash'] = true;
                    }else{
                        $item['is_wash'] = false;
                    }
                    return $item;
                })->toArray();
                $orderData['cartInfoData'] = Db::table('xd_store_order_cart_info')
                    ->whereIn('cart_id',json_decode($orderData['cart_id']))
                    ->select()
                    ->each(function ($item){
                        $item['cart_info'] = json_decode($item['cart_info']);
                        return $item;
                    });

                $goodsData = array();
                foreach($orderData['cartInfoData'] as $k => $v){
                    $goodsData[$k]['store_name'] = $v['cart_info']->productInfo->store_name;
                    $goodsData[$k]['cart_num'] = $v['cart_info']->cart_num;
                }

                $sumCart = 0;
                $cartName = [];
                foreach($goodsData as $k => $v){
                    $cartName[] = $v['store_name'].'-'.$v['cart_num'].'件';
                    $sumCart = $sumCart+$v['cart_num'];
                }

                //查询补费属性表
                $subsidy = Db::table('xd_order_subsidy_property')->select();

                $orderData['cartName'] = $cartName;
                $orderData['sumCart'] = $sumCart;
                $orderData['subsidy'] = $subsidy;
                $resData[] = $orderData;
                return response::success($resData);
            } else {
                return response::fail('订单已退款，请联系客服处理，谢谢！');
            }
        } else {
            return response::fail('查询不到该订单');
        }
    }


    /**
     * 添加订单衣物
     * @return void
     */

    public function addorderGood(Request $request)
    {
        $admin = Auth::$admin;

        $oId = $request['oId'];

        if(empty($oId)){
            return response::fail('订单号不能为空');
        }

        $orderData = Db::table('xd_store_order')->where('id|waybill_code|order_id', $oId)->find();

        if (empty($orderData)) {
            return response::fail('暂未找到该订单');
        }

        if($orderData['order_status'] == 0){
            return response::fail('该订单暂未入厂,不能执行分拣操作');
        }

        //查找空余格架号

        $res = Db::table('xd_store_order_goodsattribute')
            ->where('store_id', $admin->store_id)
            ->where('type', 10)
            ->where('order_id', $orderData['id'])
            ->find();


        if (empty($res)) {
            $screenWork = Db::table('xd_store_order_goodsattribute')
                ->where('store_id', $admin->store_id)
                ->where('type', 10)
                ->where('status', 0)
                ->find();


            $updateRes = Db::table('xd_store_order_goodsattribute')->where('id', $screenWork['id'])->update([
                'status' => 1,
                'order_id' => $orderData['id']
            ]);

            if ($updateRes == 0) {
                return response::fail('格架占用失败');
            }

            $screenWorkId = $screenWork['title'];
        } else {
            $screenWorkId = $res['title'];
        }


        $insertId = Db::table('xd_store_order_goodsInfo')->insertGetId([
            'goods_name' => '任意洗',
            'shelf_no' => $screenWorkId,
            'oid' => $orderData['id'],
            'store_id' => $admin->store_id,
            'staff_id' => $admin->id,
            'status'=>1
        ]);

//        Db::table('xd_store_order')->where('id',$orderData['id'])->update([
//            'order_status'=>2
//        ]);

        if ($insertId != 0) {
            return response::success();
        } else {
            return response::fail();
        }
    }

    /**
     * 修改订单状态
     * @param Request $request
     * @return void
     */
    public function updateOrderStatus(Request $request){

        $oId = $request['oId'];

        if(empty($oId)){
            return response::fail('订单号不能为空');
        }

        $orderData = Db::table('xd_store_order')->where('id|waybill_code|order_id', $oId)->find();

        if (empty($orderData)) {
            return response::fail('暂未找到该订单');
        }

        $goodsInfo = Db::table('xd_store_order_goodsInfo')->where('oid',$orderData['id'])->select();

        if (!empty($goodsInfo)) {
            $idsToUpdate = [];
            $currentTime = date('Y-m-d H:i:s', time());

            foreach ($goodsInfo as $k => $v) {
                if ($v['status'] < 2) {
                    $idsToUpdate[] = $v['id'];
                }
            }

            if (!empty($idsToUpdate)) {
                Db::table('xd_store_order_goodsInfo')
                    ->whereIn('id', $idsToUpdate)
                    ->update([
                        'status' => 2,
                        'add_time' => $currentTime,
                    ]);
            }
            //创建补费记录
            //查询所有需要补费的衣物
            //补费表有数据的衣物不处理
            //没有的数据新增

            $washData = Db::table('xd_store_order_goodsInfo')
                ->alias('g')
                ->field('g.*')
                ->join(['xd_order_subsidy_property' => 'sp'],'g.subsidy_id = sp.id')
                ->where('g.is_wash',0)
                ->where('sp.is_subsidy',1)
                ->where('oid',$orderData['id'])
                ->select()->toArray();


            if(!empty($washData)){
                foreach($washData as $k => $v){
                    $isFind = Db::table('xd_order_subsidy')->where('water_id',$v['id'])->find();
                    if($isFind){
                        unset($washData[$k]);
                    }
                }
            }

            if(!empty($washData)){
                //需要添加补费记录的衣物
                $insertData = array();
                $washData = array_values($washData);
                foreach($washData as $k => $v){
                    $insertData[] = [
                        'oid'=>$v['oid'],
                        'water_id'=>$v['id'],
                        'store_id'=>$v['store_id'],
                        'created_time'=>date('Y-m-d H:i:s'),
                        'cause'=>$v['no_washing_data'],
                        'is_subsidy'=>0,
                        'is_withdraw'=>0
                    ];
                }
                //添加补费记录
                if(!empty($insertData)){
                    Db::table('xd_order_subsidy')->insertAll($insertData);
                }
            }
        }

        Db::table('xd_store_order')->where('id',$orderData['id'])->update([
            'order_status'=>2
        ]);
        return response::success();
    }


    /**
     * 返回商品属性
     * @return void
     */
    public function goodsAttribute(Request $request)
    {

        $cateId = $request['cateId'];

        if (empty($cateId)) {
            return response::fail('参数错误');
        }

        $res = Db::table('xd_store_order_goodsattribute')->where('type', $cateId)->select()->toArray();

        return response::success($res);

    }


    /**
     * 删除衣物
     */

    public function removeGoodsInfo(Request $request)
    {

        $admin = Auth::$admin;
        //水洗唛id
        $id = $request['id'];

        Db::table('xd_store_order_goodsInfo')
            ->where('id', $id)
            ->delete();

        return response::success();
    }


    /**
     * 修改衣物属性
     * @return void
     */
    public function editAttribute(Request $request)
    {

        //水洗唛
        $id = $request['id'];
        $goods_flaw = $request['goods_flaw'];
        $fidjson = $request['fidjson'];
        $pic = $request['pic'];
        $goodsName = $request['goods_name'];
        $goodsColor = $request['goods_color'];
        $isWash = $request['is_wash'];
        $noWashingData = $request['no_washing_data'];
        $subsidyId = $request['subsidy_id'];


        $update = array();
        //数据处理

        if(!empty($goodsName)){
            $update['goods_name'] = $goodsName;
        }

        if(!empty($goodsColor)){
            $update['goods_color'] = $goodsColor;
        }

        if(!empty($goods_flaw)){
            foreach($goods_flaw as $k => $v){
                $goodsFlaw[$k]['id'] = $v['id'];
                $goodsFlaw[$k]['title'] = $v['title'];
            }
            $goodsFlaw = json_encode($goodsFlaw);

            $update['goods_flaw'] = $goodsFlaw;
        }

        if(!empty($fidjson)){
            foreach($fidjson as $k => $v){
                $fidJson[$k]['id'] = $v['id'];
                $fidJson[$k]['code'] = $v['code'];
                $fidJson[$k]['title'] = $v['title'];
            }
            $fidJson = json_encode($fidJson);

            $update['fidjson'] = $fidJson;
        }

        if(!empty($pic)){
            $update['pic'] = json_encode($pic);
        }

        if(!empty($isWash)){
            if($isWash == 2){
                $isWash = 0;
            }else{
                $update['no_washing_data'] = '';
            }

            $update['is_wash'] = $isWash;
        }

        if(!empty($noWashingData)){
            $update['is_wash'] = 0;
            $update['no_washing_data'] = $noWashingData;
            $update['subsidy_id'] = $subsidyId;
        }

        $res = Db::table('xd_store_order_goodsInfo')->where('id',$id)->update($update);

        return response::success();


//        if (!empty($id)) {
//            if ($type == 1) {
//                //衣服
//                $arr = array(
//                    'goods_name' => $title,
//                );
//            } else if ($type == 2) {
//                //颜色
//                $arr = array(
//                    'goods_color' => $title
//                );
//
//            } else if ($type == 3) {
//                //瑕疵
//                //title为数组
//
//                Db::table('xd_store_order_goodsInfo')->where('id', $id)->update([
//                    'goods_flaw' => json_encode($title)
//                ]);
//
//                return response::success();
//
//            } else if ($type == 4) {
//
//                //附件
//                Db::table('xd_store_order_goodsInfo')->where('id', $id)->update([
//                    'fidjson' => json_encode($title)
//                ]);
//
//                return response::success();
//
//            } else if ($type == 5) {
//
//                //洗涤要求
//
//                return response::success();
//            } else if ($type == 6) {
//
//                //品牌
//                return response::success();
//            } else if ($type == 7) {
//
//                //异常
//                return response::success();
//            } elseif ($type == 8) {
//
//                //拍照
//                Db::table('xd_store_order_goodsInfo')->where('id', $id)->update([
//                    'pic' => json_encode($pic)
//                ]);
//
//            } else {
//                return response::fail('参数错误');
//            }
//
//            Db::table('xd_store_order_goodsInfo')->where('id', $id)->update($arr);
//
//            return response::success();
//        } else {
//            return response::fail('参数错误');
//        }
    }


    /**
     * 通过水洗唛查找衣物
     * @return void
     */
    public function getGoodsInfo(Request $request)
    {

        $id = $request['id'];

        if (empty($id)) {
            return response::fail('参数错误');
        }

        $data = Db::table('xd_store_order_goodsInfo')
            ->alias('a')
            ->join(['xd_store_order' => 'b'], 'b.id = a.oid')
            ->field('a.*,a.id as gid,a.status as g_status,b.id as orderId,b.*')
            ->where('a.id', $id)
            ->find();

        //获取总件数
        if (!empty($data)) {
            $data['count'] = Db::table('xd_store_order_goodsInfo')->where('oid', $data['oid'])->count();
        } else {
            return response::fail('水洗码错误');
        }

        $data['fidjson'] = json_decode($data['fidjson']);
        $data['pic'] = json_decode($data['pic']);
        $data['goods_flaw'] = json_decode($data['goods_flaw']);

        return response::success($data);
    }


    /**
     * 污渍终止标记
     */
    public function goodsStain(Request $request)
    {

        $admin = Auth::$admin;

        //水洗唛
        $id = $request['id'];
        $type = $request['type'];
        //1  标记    2  取消标记

        if (empty($id) || empty($type)) {
            return response::fail('参数错误');
        }

        if($type == 2){
            $type = 0;
        }

        $res = Db::table('xd_store_order_goodsInfo')
            ->where('id', $id)
            ->update([
                'termination' => $type,
                'termination_id' => $admin['id'],
                'termination_date' => date('Y-m-d H:i:s'),
                'zongjiantime' => date('Y-m-d H:i:s'),
                'status'=>3,
                'examine_id'=>$admin->id
            ]);

        //查找订单号
        $infoData = Db::table('xd_store_order_goodsInfo')->where('id',$id)->find();

        DB::table('xd_store_order')->where('id',$infoData['oid'])->update(['order_status'=>3]);

        //返回已总检衣物和未总检衣物
        $noPutAway = Db::table('xd_store_order_goodsInfo')
            ->alias('g')
            ->field('g.*,o.remark,o.mark,o.order_id,o.waybill_code')
            ->join(['xd_store_order'=>'o'],'o.id = g.oid')
            ->where('g.oid', $infoData['oid'])
            ->where('g.status', '<', 3)
            ->select()->each(function ($item){
                $item['fidjson'] = json_decode($item['fidjson']);
                $item['pic'] = json_decode($item['pic']);
                $item['goods_flaw'] = json_decode($item['goods_flaw']);
                return $item;
            });


        $PutAway = Db::table('xd_store_order_goodsInfo')
            ->alias('g')
            ->field('g.*,o.remark,o.mark,o.order_id,o.waybill_code')
            ->join(['xd_store_order'=>'o'],'o.id = g.oid')
            ->where('g.oid', $infoData['oid'])
            ->where('g.status', '>=', 3)
            ->select()->each(function ($item){
                $item['fidjson'] = json_decode($item['fidjson']);
                $item['pic'] = json_decode($item['pic']);
                $item['goods_flaw'] = json_decode($item['goods_flaw']);
                return $item;
            });

        if ($res != 0) {
            return response::success([
                'examine'=>$PutAway,
                'noExamine' => $noPutAway
            ]);
        } else {
            return response::fail();
        }
    }


    /**
     * 总检
     */
    public function examine(Request $request)
    {

        $admin = Auth::$admin;

        $id = $request['id'];
        $status = $request['status'];
        //1  总检    2 取消总检

        if (empty($id) || empty($status)) {
            return response::fail('参数错误');
        }

        if ($status == 1) {
            $update = [
                'status' => 3,
                'zongjiantime' => date('Y-m-d H:i:s'),
                'examine_id' => $admin['id']
            ];

            $orderUpdate = [
                'order_status'=>3
            ];
        } else {
            $update = [
                'status' => 2,
                'zongjiantime' => date('Y-m-d H:i:s'),
                'examine_id' => $admin['id']
            ];
            $orderUpdate = [
                'order_status'=>3
            ];
        }

        $res = Db::table('xd_store_order_goodsInfo')->where('id', $id)->update($update);

        //查找订单号
        $infoData = Db::table('xd_store_order_goodsInfo')->where('id',$id)->find();

        DB::table('xd_store_order')->where('id',$infoData['oid'])->update($orderUpdate);

        //返回已总检衣物和未总检衣物
        $noPutAway = Db::table('xd_store_order_goodsInfo')
            ->alias('g')
            ->field('g.*,o.remark,o.mark,o.order_id,o.waybill_code')
            ->join(['xd_store_order'=>'o'],'o.id = g.oid')
            ->where('g.oid', $infoData['oid'])
            ->where('g.status', '<', 3)
            ->select()->each(function ($item){
                $item['fidjson'] = json_decode($item['fidjson']);
                $item['pic'] = json_decode($item['pic']);
                $item['goods_flaw'] = json_decode($item['goods_flaw']);
                return $item;
            });


        $PutAway = Db::table('xd_store_order_goodsInfo')
            ->alias('g')
            ->field('g.*,o.remark,o.mark,o.order_id,o.waybill_code')
            ->join(['xd_store_order'=>'o'],'o.id = g.oid')
            ->where('g.oid', $infoData['oid'])
            ->where('g.status', '>=', 3)
            ->select()->each(function ($item){
                $item['fidjson'] = json_decode($item['fidjson']);
                $item['pic'] = json_decode($item['pic']);
                $item['goods_flaw'] = json_decode($item['goods_flaw']);
                return $item;
            });

        if ($res != 0) {
            return response::success([
                'examine'=>$PutAway,
                'noExamine' => $noPutAway
            ]);
        } else {
            return response::fail();
        }
    }


    /**
     * 当日质检
     */

    public function todayExamine(Request $request)
    {

        $admin = Auth::$admin;

        $size = $request['size'] ?? 15;
        $page = $request['page'] ?? 1;

        if($admin->roles == 0){
            $where = [
                ['store_id','=',$admin->store_id],
            ];
        }else{
            $where = [
                ['staff_id','=',$admin->id],
            ];
        }

        $data = Db::table('xd_store_order_goodsInfo')
            ->where($where)
            ->where('status', 3)
            ->whereBetweenTime('zongjiantime', '2023-10-17', '2023-10-18')
            ->paginate($size)->each(function ($item) {
                $item['pic'] = json_decode($item['pic']);
                $item['goods_flaw'] = json_decode($item['goods_flaw']);
                $item['fidjson'] = json_decode($item['fidjson']);
                return $item;
            });

        return response::success($data);
    }

    /**
     * 上架
     * @return void
     */
    public function putaway(Request $request)
    {

        $id = $request['id'];
        $admin = Auth::$admin;

        $goodsData = Db::table('xd_store_order_goodsInfo')->where('id', $id)->find();

        DB::table('xd_store_order')->where('id',$goodsData['oid'])->update(['order_status'=>5]);

        if (empty($goodsData)) {
            return response::fail('水洗码错误');
        }

        Db::table('xd_store_order_goodsInfo')->where('id', $id)->update([
            'status' => 5,
            'putaway_id' => $admin['id'],
            'putaway_date' => date('Y-m-d H:i:s')
        ]);

        //返回已上架衣物和未上架衣物
        $noPutAway = Db::table('xd_store_order_goodsInfo')
            ->alias('g')
            ->field('g.*,o.remark,o.mark,o.order_id')
            ->join(['xd_store_order'=>'o'],'o.id = g.oid')
            ->where('g.oid', $goodsData['oid'])
            ->where('g.status', '<', 5)
            ->select()->each(function ($item){
                $item['fidjson'] = json_decode($item['fidjson']);
                $item['pic'] = json_decode($item['pic']);
                $item['goods_flaw'] = json_decode($item['goods_flaw']);
                return $item;
            });


        $PutAway = Db::table('xd_store_order_goodsInfo')
            ->alias('g')
            ->field('g.*,o.remark,o.mark,o.order_id')
            ->join(['xd_store_order'=>'o'],'o.id = g.oid')
            ->where('g.oid', $goodsData['oid'])
            ->where('g.status', '>=', 5)
            ->select()->each(function ($item){
                $item['fidjson'] = json_decode($item['fidjson']);
                $item['pic'] = json_decode($item['pic']);
                $item['goods_flaw'] = json_decode($item['goods_flaw']);
                return $item;
            });

        return response::success([
            'noPutAway'=>$noPutAway,
            'putAway'=>$PutAway
        ]);
    }


    /**
     * 衣物打包 并自动出厂
     */

    public function packDeliver(Request $request){

        $admin = Auth::$admin;
        //水洗码
        $id = $request['id'];

        if(empty($id)){
            return response::fail('参数错误');
        }

        $res = Db::table('xd_store_order_goodsInfo')->where('id',$id)->find();

        if(empty($res)){
            return response::fail('未找到衣物');
        }

        DB::table('xd_store_order')->where('id',$res['oid'])->update(['order_status'=>6]);


        Db::table('xd_store_order_goodsInfo')->where('id',$id)->update([
            'status'=>6,
            'pack_id'=>$admin['id'],
            'pack_date'=>date('Y-m-d H:i:s')
        ]);


        //返回已打包衣物和未打包衣物
        $noPack = Db::table('xd_store_order_goodsInfo')
            ->alias('g')
            ->field('g.*,o.remark,o.mark,o.order_id,o.waybill_code')
            ->join(['xd_store_order'=>'o'],'o.id = g.oid')
            ->where('g.oid', $res['oid'])
            ->where('g.status', '<', 6)
            ->select()->each(function ($item){
                $item['fidjson'] = json_decode($item['fidjson']);
                $item['pic'] = json_decode($item['pic']);
                $item['goods_flaw'] = json_decode($item['goods_flaw']);
                return $item;
            })->toArray();


        $pack = Db::table('xd_store_order_goodsInfo')
            ->alias('g')
            ->field('g.*,o.remark,o.mark,o.order_id,o.waybill_code')
            ->join(['xd_store_order'=>'o'],'o.id = g.oid')
            ->where('g.oid', $res['oid'])
            ->where('g.status', '>=', 6)
            ->select()->each(function ($item){
                $item['fidjson'] = json_decode($item['fidjson']);
                $item['pic'] = json_decode($item['pic']);
                $item['goods_flaw'] = json_decode($item['goods_flaw']);
                return $item;
            })->toArray();


        //判断衣物是否打包完成
        if(empty($noPack)){
            $data = Db::table('xd_store_order')->where('id',$res['oid'])->find();
            if(empty($data['delivery_id'])){
                //自动下单
                $orderModel = new orderModel();
                $factory = $orderModel->leaveFactory($res['oid'],$admin);
                if($factory['code'] == 1000){
                    $msg = $factory['msg'];
                    $print = 0;
                    return response::fail($msg);
                }else{
                    //空出格架号
                    Db::table('xd_store_order_goodsattribute')->where('order_id',$res['oid'])->update([
                        'order_id'=>'',
                        'status'=>0
                    ]);
                    return response::success([
                        'no_pack'=>$noPack,
                        'pack'=>$pack,
                        'print'=>1
                    ]);
                }
            }
        }
        return response::success([
            'no_pack'=>$noPack,
            'pack'=>$pack
        ]);
    }


    /**
     * 补单
     * @return void
     */
    public function replenishmentOrder(Request $request){

        $admin = Auth::$admin;
        $oId = $request['id'];
        $orderData = Db::table('xd_store_order')->where('id',$oId)->find();
        if(empty($orderData)){
            return response::fail('未找到该订单');
        }

        if(!empty($orderData['delivery_id'])){
            return response::fail('该订单已有出厂运单号');
        }

        $orderModel = new orderModel();
        $factory = $orderModel->leaveFactory($oId,$admin);
        if($factory['code'] == 1000){
            $msg = $factory['msg'];
            return response::fail($msg);
        }else{
            //空出格架号
            Db::table('xd_store_order_goodsattribute')->where('order_id',$oId)->update([
                'order_id'=>'',
                'status'=>0
            ]);
            return response::success($factory['data']);
        }
    }


//    /**
//     * 出厂
//     */
//
//    public function leaveFactory(Request $request){
//
//        $admin = Auth::$admin;
//        $oId = $request['oId'];
//
//        //查询订单下是否还有未打包的衣物
//
//        $data = Db::table('xd_store_order_goodsInfo')->where('oId',$oId)->where('status','<>',6)->select()->toArray();
//
//        if(!empty($data)){
//
//            $msg = array();
//            foreach($data as $v){
//                $msg[] = $v['id'];
//            }
//
//            $msgData = implode('/',$msg);
//
//            return response::fail('该订单下还有未打包的衣物,水洗码为'.$msgData);
//        }
//
//        $orderModel = new orderModel();
//        $factory = $orderModel->leaveFactory($oId,$admin);
//
//        if($factory['code']== 1000){
//            return response::fail($factory['msg']);
//        }
//
//        DB::table('xd_store_order')->where('id',$oId)->update(['order_status'=>4]);
//
//        return response::success();
//    }


    /**
     * 订单列表
     */

    public function orderList(Request $request){

        $admin = Auth::$admin;
        $page = $request['page'] ?? 1;
        $size = $request['size'] ?? 10;
        $search = $request['search'];
        $importance = $request['importance'];

        if($admin->roles == 0){
            $where = [
                ['store_id','=',$admin->store_id],
            ];
        }else{
            $where = [
                ['staff_id','=',$admin->id],
            ];
        }

        if($importance == 1){
            // 已出厂

            $where[] = [
                ['order_status','=',7],
            ];

        }else{
            //未出厂
            $where[] = [
                ['order_status','<',7],
            ];
        }

        $data = Db::table('xd_store_order')
            ->where($where)
            ->whereLike('order_id|user_phone|id','%'.$search.'%')
            ->order('id','desc')
            ->paginate($size);

        return response::success($data);
    }


    /**
     * 订单查看详情
     * @return void
     */
    public function orderListInfo(Request $request){

        $oid = $request['oid'];

        $orderData = Db::table('xd_store_order')->where('id',$oid)->find();
        $goodsInfo = Db::table('xd_store_order_goodsInfo')->where('oid',$oid)->select()->toArray();

        $orderData['goodsInfo']=$goodsInfo;

        return response::success($orderData);

    }


    /**
     * 衣物列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function laundryList(Request $request){

        $page = $request['page'] ?? 1;
        $size = $request['size'] ?? 10;
        $search = $request['search'];


        $data = Db::table('xd_store_order_goodsInfo')
            ->alias('g')
            ->field('o.id,o.order_id,o.real_name,o.user_phone,o.user_address,o.delivery_id,o.delivery_name,o.mark,o.waybill_code,g.*')
            ->join(['xd_store_order'=>'o'],'g.oid = o.id')
            // ->whereLike('o.order_id|o.user_phone|g.id','%'.$search.'%')
            ->paginate($size)->each(function ($item){
                $item['fidjson'] = json_decode($item['fidjson']);
                $item['pic'] = json_decode($item['pic']);
                $item['goods_flaw'] = json_decode($item['goods_flaw']);
                return $item;
            });

        return response::success($data);

    }


    /**
     * 数据统计
     * @return void
     */
    public function statisticsData(){

        $admin = Auth::$admin;

        $now = date('Y-m-d H:i:s');

        $thirtyDaysAgo = date('Y-m-d H:i:s', strtotime('-30 days', strtotime($now)));

        $query = Db::query("SELECT 
    Date,
    SUM(RecordCountZongjiantime) AS RecordCountZongjiantime,
    SUM(RecordCountPutawayDate) AS RecordCountPutawayDate,
    SUM(RecordCountTerminationDate) AS RecordCountTerminationDate,
    SUM(RecordCountPackDate) AS RecordCountPackDate,
    SUM(RecordCountSorting) AS RecordCountSorting,
    SUM(factoryCount) AS factoryCount
FROM (
    SELECT DATE(zongjiantime) AS Date, 
        COUNT(*) AS RecordCountZongjiantime,
        0 AS RecordCountPutawayDate,
        0 AS RecordCountTerminationDate,
        0 AS RecordCountPackDate,
        0 AS RecordCountSorting,
        0 AS factoryCount
    FROM xd_store_order_goodsInfo
    WHERE zongjiantime >= ? AND zongjiantime <= ? And store_id = {$admin->store_id}
    GROUP BY Date
    UNION ALL
    SELECT DATE(putaway_date) AS Date, 
        0 AS RecordCountZongjiantime,
        COUNT(*) AS RecordCountPutawayDate,
        0 AS RecordCountTerminationDate,
        0 AS RecordCountPackDate,
        0 AS RecordCountSorting,
        0 AS factoryCount
    FROM xd_store_order_goodsInfo
    WHERE putaway_date >= ? AND putaway_date <= ? And store_id = {$admin->store_id}
    GROUP BY Date
    UNION ALL
    SELECT DATE(termination_date) AS Date, 
        0 AS RecordCountZongjiantime,
        0 AS RecordCountPutawayDate,
        COUNT(*) AS RecordCountTerminationDate,
        0 AS RecordCountPackDate,
        0 AS RecordCountSorting,
        0 AS factoryCount
    FROM xd_store_order_goodsInfo
    WHERE termination_date >= ? AND termination_date <= ? And store_id = {$admin->store_id}
    GROUP BY Date
    UNION ALL
    SELECT DATE(pack_date) AS Date, 
        0 AS RecordCountZongjiantime,
        0 AS RecordCountPutawayDate,
        0 AS RecordCountTerminationDate,
        COUNT(*) AS RecordCountPackDate,
        0 AS RecordCountSorting,
        0 AS factoryCount
    FROM xd_store_order_goodsInfo
    WHERE pack_date >= ? AND pack_date <= ? And store_id = {$admin->store_id}
    GROUP BY Date
    UNION ALL
    SELECT DATE(create_time) AS Date, 
        0 AS RecordCountZongjiantime,
        0 AS RecordCountPutawayDate,
        0 AS RecordCountTerminationDate,
        0 AS RecordCountPackDate,
        COUNT(*) AS RecordCountSorting,
        0 AS factoryCount
    FROM xd_store_order_goodsInfo
    WHERE create_time >= ? AND create_time <= ? And store_id = {$admin->store_id}
    GROUP BY Date
    UNION ALL
    SELECT DATE(factory_time) AS Date, 
        0 AS RecordCountZongjiantime,
        0 AS RecordCountPutawayDate,
        0 AS RecordCountTerminationDate,
        0 AS RecordCountPackDate,
        0 AS RecordCountSorting,
        COUNT(*) AS factoryCount
    FROM xd_store_order
    WHERE factory_time >= ? AND factory_time <= ? And store_id = {$admin->store_id}
    GROUP BY Date
) AS Subquery
GROUP BY Date
ORDER BY Date DESC
", [
            $thirtyDaysAgo, $now, $thirtyDaysAgo, $now, $thirtyDaysAgo, $now, $thirtyDaysAgo, $now, $thirtyDaysAgo, $now, $thirtyDaysAgo, $now
        ]);

        return Response::success($query);
    }


    public function upload()
    {
        $accessKey = self::APPKEY;
        $secretKey = self::SECRET;
        $bucket = self::BUCKET;
        $domain = self::DOMAIN;

        $auth = new QiNiuAuth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        if (request()->isPost()) {
            $file = str_replace('"','',$_POST['file']);
            if ($file) {
                $uploadMgr = new UploadManager();
                $key = time() . rand(1000, 9999);
                list($ret, $err) = $uploadMgr->putFile($token, $key, $file);
                if ($err !== null) {
                    return response::fail('文件上传失败');
                } else {
                    $url = $domain . '/' . $ret['key'];
                    return response::success($url);
                }
            }
        }
        return response::fail('参数错误');
    }


    public function uploadFile()
    {
        $accessKey = self::APPKEY;
        $secretKey = self::SECRET;
        $bucket = self::BUCKET;
        $domain = self::DOMAIN;

        $auth = new QiNiuAuth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        if (request()->isPost()) {
//            $file = str_replace('"','',$_POST['file']);
            $file = request()->file('file');
            if ($file) {
                $uploadMgr = new UploadManager();
                $key = time() . rand(1000, 9999);
                list($ret, $err) = $uploadMgr->putFile($token, $key, $file);
                if ($err !== null) {
                    return response::fail('文件上传失败');
                } else {
                    $url = $domain . '/' . $ret['key'];
                    return response::success($url);
                }
            }
        }
        return response::fail('参数错误');
    }

    public function jdPrint(){


        $temeplate = 'https://template-content.jd.com/template-oss?tempCode=jdky100x113';
//给jd下单
//        $baseUri = "https://api.jdl.com";
        $baseUri = "https://uat-api.jdl.com";
        $appKey = "1eb37f16f53b4982ab5f87c852cef46e";
        $appSecret = "23b2f268e08140a1837de4df94e2e77b";
//        $accessToken = "b3b2cc3e002f4c3d83311c8eb54efae4";
        $accessToken = "fe3a886e6ff24def9d56addaf615b93d";

        $domain = "ECAP";
        $path = "/cloud/print/getTemplates";
        $method = "post";
        $algorithm = "md5-salt";
        $jdkey = '028K2835294';
        $body = '[
                   {
                        "cpCode":"JDKY",
                        "templateType":
                    }
                  ]';

        $data = json_encode(json_decode($body,true));
        $timestamp = date("Y-m-d H:i:s");
        $content = implode("", array(
            $appSecret,
            "access_token", $accessToken,
            "app_key", $appKey,
            "method", $path,
            "param_json", $data,
            "timestamp", $timestamp,
            "v", "2.0",
            $appSecret
        ));

        $sign = md5($content);

        $query = http_build_query(array(
            "LOP-DN" => $domain,
            "app_key" => $appKey,
            "access_token" => $accessToken,
            "timestamp" => $timestamp,
            "v" => "2.0",
            "sign" => $sign,
            "algorithm" => $algorithm
        ));

        $uri = $baseUri . $path . "?" . $query;

        $data12  = Helper::http_request($uri,$data);

        return response::success($data12);
    }


    /**
     * 衣物列表
     * @return void
     */
    public function clothingData(Request $request){

        $admin = Auth::$admin;

        $page = $request['page'] ?? 1;
        $size = $request['size'] ?? 10;
        $search = $request['search'];


        $data = Db::table('xd_store_order_goodsInfo')
            ->alias('og')
            ->field('og.*,o.order_id,o.mark,o.remark')
            ->join(['xd_store_order'=>'o'],'o.id=og.oid')
            ->whereLike('og.id|o.order_id','%'.$search.'%')
            ->where('og.store_id',$admin->store_id)
            ->order('og.id','desc')
            ->paginate($size)->each(function ($item){
                    $item['pic'] = json_decode($item['pic']);
                    $item['goods_flaw'] = json_decode($item['goods_flaw']);
                    $item['fidjson'] = json_decode($item['fidjson']);
                    return $item;
            });

        return response::success($data);
    }



    /**
     * 补费列表
     */
    public function subsidyData(Request $request){

        $admin = Auth::$admin;
        $oid = $request['oid'];
        $size = $request['size'];

        $data = Db::table('xd_order_subsidy')
            ->where('store_id',$admin->store_id)
            ->whereLike('oid|water_id','%'.$oid.'%')
            ->order('id','desc')
            ->paginate($size);

        return response::success($data);
    }

    /**
     * 撤回补费
     */
    public function revocationSubsidy(Request $request){
        $admin = Auth::$admin;
        $id = $request['id'];

        $data = Db::table('xd_order_subsidy')->where('id',$id)->where('store_id',$admin->store_id)->find();

        if(empty($data)){
            return response::fail('暂未找到该补费记录');
        }

        if($data['is_subsidy'] == 1){
            return response::fail('该订单已补费,无法撤回,请联系商家');
        }

        Db::table('xd_order_subsidy')->where('id',$id)->update([
            'is_withdraw'=>1,
            'withdraw_time'=>date('Y-m-d H:i:s')
        ]);

        return response::success();
    }


}
